package guid

import (
	"bytes"
	"context"
	"fmt"
	"github.com/wutianze/nats.go"
	apis2 "gluenet/pkg/apis"
	"gluenet/pkg/log/v1"
	"gluenet/pkg/nets"
)

type Service struct {
	ctx    context.Context
	logger v1.Logger

	fs map[string]*nats.Subscription
}

func NewGuidService(ctx context.Context) *Service {
	return &Service{
		ctx: ctx,
		fs:  make(map[string]*nats.Subscription),
	}
}

func (r *Service) Run(logger v1.Logger, c *apis2.GlueContext) {
	r.logger = logger

	i, err := c.Rpc.Subscribe(apis2.GuidServiceRegister, func(m nets.NetContext) {
		register(apis2.GlueContext{
			Context:    r.ctx,
			Validate:   c.Validate,
			Logger:     logger,
			DataBase:   c.DataBase,
			Rpc:        c.Rpc,
			RpcContext: &m,
		})
	})
	if err != nil {
		r.logger.Fatalf("guid service register :%v", err)
	}
	r.fs[apis2.GuidServiceRegister] = i

	i2, err := c.Rpc.Subscribe(apis2.GuidServiceUnRegister, func(m nets.NetContext) {
		register(apis2.GlueContext{
			Context:    r.ctx,
			Validate:   c.Validate,
			Logger:     logger,
			DataBase:   c.DataBase,
			Rpc:        c.Rpc,
			RpcContext: &m,
		})
	})
	if err != nil {
		r.logger.Fatalf("guid service unregister :%v", err)
	}
	r.fs[apis2.GuidServiceUnRegister] = i2
}

func (r *Service) Close() error {
	errs := new(bytes.Buffer)
	for k, v := range r.fs {
		if err := v.Unsubscribe(); err != nil {
			errs.WriteString(fmt.Sprintf("unregister %v %v\n", k, err))
		}
	}

	if errs.Len() <= 0 {
		return nil
	} else {
		return fmt.Errorf("%v", errs.String())
	}
}
